﻿/******************************************************************************
 *  作者：       Maxzhang1985
 *  创建时间：   2012/5/2 14:58:24
 *
 *
 ******************************************************************************/
using System;
using System;
using System.Web;
using System.IO;
using NVelocity;
using NVelocity.App;
using NVelocity.Context;
using NVelocity.Runtime;
using Commons.Collections;

namespace ExORMDesginer.Plugin.Template
{


    /// <summary>
    /// NVelocity模板工具类 VelocityHelper
    /// </summary>
    public class VelocityHelper
    {
        private VelocityEngine velocity = null;
        private IContext context = null;

        /// 
        /// 构造函数
        /// 
        ///模板文件夹路径
        public VelocityHelper(string templatDir)
        {
            Init(templatDir);
        }
        /// 
        /// 无参数构造函数
        /// 
        public VelocityHelper() { ;}
     
        /// <summary>
        ///初始话NVelocity模块
        /// </summary>
        /// <param name="templatDir">模板文件夹路径</param>
        public void Init(string templatDir)
        {
            //创建VelocityEngine实例对象
            velocity = new VelocityEngine();

            //使用设置初始化VelocityEngine
            ExtendedProperties props = new ExtendedProperties();
            props.AddProperty(RuntimeConstants.RESOURCE_LOADER, "file");
            props.AddProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, templatDir);
            props.AddProperty(RuntimeConstants.INPUT_ENCODING, "gb2312");
            props.AddProperty(RuntimeConstants.OUTPUT_ENCODING, "gb2312");
            velocity.Init(props);

            //为模板变量赋值
            context = new VelocityContext();
        }
        
        /// <summary>
        /// 给模板变量赋值
        /// </summary>
        /// <param name="key"></param>
        /// <param name="value"></param>
        public void Put(string key, object value)
        {
            if (context == null)
                context = new VelocityContext();
            context.Put(key, value);
        }


        public string GetResult(string name)
        {
            StringWriter writer = new StringWriter();
            var template = velocity.GetTemplate(name);
            template.Merge(context, writer);
            return writer.GetStringBuilder().ToString();
        }

    }
}